//
//  FYUserViewModel.m
//  ThePainter
//
//  Created by Sean on 15/9/11.
//  Copyright (c) 2015年 FeiYu. All rights reserved.
//

#import "FYUserViewModel.h"
#import "FYProduct.h"
#import "FYCache.h"
#import "FYUserPageModel.h"


static int pageNum = 0;

@implementation FYUserViewModel

- (void)loadNewData:(id)key valueBlock:(ReturnValueBlock)valueBlock errorBlock:(ErrorCodeBlock)errorBlock failureBlock:(FailureBlock)failureBlock {
    
    //-------测试数据----------
    NSString *path = [[NSBundle mainBundle] pathForResource:@"FYUserPageData" ofType:@""];
    NSString *productsStr = [NSString stringWithContentsOfFile:path encoding:NSUTF8StringEncoding error:nil];
    NSDictionary *dic = [FYUtils fyJsonToDictionary:productsStr];
    
    
    //缓存list到内存
    [[FYCache shareInstance] setUserPageModelCache:dic];
    
    pageNum = 10;
    NSArray *arr = dic[@"products"];
    NSArray *temp = [arr subarrayWithRange:NSMakeRange(0, arr.count > pageNum ? pageNum : arr.count)];
    
    FYUserPageModel *model = [FYUserPageModel objectWithKeyValues:dic];
    model.products = [FYProduct objectArrayWithKeyValuesArray:temp];
    
    //刷新列表
    valueBlock(model);
}

- (void)loadMoreData:(id)key valueBlock:(ReturnValueBlock)valueBlock errorBlock:(ErrorCodeBlock)errorBlock failureBlock:(FailureBlock)failureBlock {

    //如果是最后一个，不再获取数据
    if (pageNum == -1) {
        failureBlock();
        return;
    }
    //页数增加
    pageNum += 10;
    //从cache获取数据
    NSDictionary *dic = [FYCache shareInstance].userPageModelCache;
    //获取前pageNum条
    NSArray *arr = dic[@"products"];
    NSArray *temp = [arr subarrayWithRange:NSMakeRange(0, pageNum < arr.count ? pageNum : (int)arr.count)];
    //转成jsonmodel
    FYUserPageModel *model = [FYUserPageModel objectWithKeyValues:dic];
    model.products = [FYProduct objectArrayWithKeyValuesArray:temp];
    //刷新列表
    valueBlock(model);
    //如果已经是最后一个，设置pageNum的标志位-1
    pageNum = pageNum < arr.count ? pageNum : -1;
}

@end
